package com.aixin.csopservice.controller;


import com.aixin.common.core.domain.model.LoginUser;
import com.aixin.common.core.redis.RedisCache;
import com.aixin.common.utils.DateUtils;
import com.aixin.common.utils.ServletUtils;
import com.aixin.csopservice.domain.ExcelDomain;
import com.aixin.csopservice.service.ExcelService;
import com.aixin.csopservice.utils.ExcelHelper;
import com.aixin.csopservice.utils.ExcelUtil;
import com.aixin.csopservice.utils.Util;
import com.aixin.csopsupplier.domain.ServiceDef;
import com.aixin.csopsupplier.domain.SupplierDef;
import com.aixin.csopsupplier.service.ServiceDefService;
import com.aixin.csopsupplier.service.SupplierDefService;
import com.aixin.csopuser.domain.CustomerDomain;
import com.aixin.csopuser.domain.CustomerServiceConsume;
import com.aixin.csopuser.domain.SupplierCustomerDomain;
import com.aixin.csopuser.domain.dto.SupplierCustomerDTO;
import com.aixin.csopuser.domain.vo.CustomerServiceConsumeQuery;
import com.aixin.csopuser.model.CustomerModel;
import com.aixin.csopuser.model.SupplierCustomerModel;
import com.aixin.csopuser.service.CustomerService;
import com.aixin.csopuser.service.CustomerServiceConsumeService;
import com.aixin.framework.web.service.TokenService;
import com.github.pagehelper.PageInfo;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestPart;

import java.io.InputStream;
import java.util.*;
import java.io.FileInputStream;
import java.io.*;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.zip.DataFormatException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/excel")
@EnableAutoConfiguration
public class ExcelController {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    ServiceDefService serviceDefService;

    @Autowired
    SupplierDefService supplierDefService;

    @Autowired
    ExcelService excelService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private CustomerServiceConsumeService customerServiceConsumeService;

    private static int PAGE_SIZE = 3000;

    /**
     * 服务项目Excel上传
     * 余照洋  任务
     */
    @PostMapping(value = "/upLoadServiceDef")
    @CrossOrigin
    public ExcelDomain upLoadServiceDef(@RequestPart("file") MultipartFile multipartFile) throws IOException {
        multipartFile.getOriginalFilename();


//        Path tempFile = Files.createTempFile("temp",filePart.filename());
//        //上传文件
//        filePart.transferTo(tempFile.toFile());
//        //转换文件流
//        InputStream inputStream = new FileInputStream(tempFile.toFile());
//        //读取excel
        ExcelDomain excelDomain = readExcelFile(multipartFile.getInputStream(), multipartFile.getOriginalFilename());
//        //删除临时文件
//        Files.delete(tempFile);
        if ("SUCCESS".equals(excelDomain.getSuccess())) {
            serviceDefService.excelImport(excelDomain.getServiceDefList());
            return excelDomain;
        }
        return excelDomain;
    }

    /**
     * 读取服务项目Excel
     */
    private ExcelDomain readExcelFile(InputStream inputStream, String fileName) {
        ExcelDomain excelDomain = new ExcelDomain();
        List<ServiceDef> serviceDefs = new ArrayList<>();
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        List<SupplierDef> supplierList = redisCache.getCacheObject("supplierList");
        if (supplierList == null) {
            supplierList = supplierDefService.findAll();
        }

        try {
            Map<String, String> titleMap = new HashMap();
            titleMap.put("权益项目名称", "serviceName");
            titleMap.put("权益项目内容详情", "serviceIntr");
            titleMap.put("使用流程", "serviceProcess");
            titleMap.put("使用通道", "serviceChannel");
            titleMap.put("权益提供方", "supplierName");
            titleMap.put("有效期", "termOfValidity");
            list = ExcelUtil.readExcel(inputStream, fileName, titleMap);

            for (Map<String, Object> map : list) {
                ServiceDef serviceDef = new ServiceDef();
                String supplierID = null;
                if (null == map.get("serviceName") | "".equals(map.get("serviceName"))) {
                    excelDomain.setMessage("权益项目名称不能为空");
                    excelDomain.setSuccess("FALSE");
                    return excelDomain;
                }
                if (null == map.get("supplierName") | "".equals(map.get("supplierName"))) {
                    excelDomain.setMessage("权益提供方不能为空");
                    excelDomain.setSuccess("FALSE");
                    return excelDomain;
                }
                if (null == map.get("termOfValidity") | "".equals(map.get("termOfValidity"))) {
                    excelDomain.setMessage("有效期不能为空");
                    excelDomain.setSuccess("FALSE");
                    return excelDomain;
                }


                Calendar calendar = new GregorianCalendar(1900, 0, -1);
                Date d = calendar.getTime();
                Date tremDate = DateUtils.addDays(d, Integer.valueOf(Integer.valueOf(map.get("termOfValidity").toString())));
                String termOfValidity = Util.dateFormat(tremDate);

                for (SupplierDef supplierDef : supplierList) {
                    if (supplierDef.getSupplierName().equals(map.get("supplierName"))) {
                        supplierID = supplierDef.getSupplierID();
                        break;
                    }
                }
                if (supplierID == null) {
                    excelDomain.setMessage("请核实项目为:" + map.get("serviceName") + "的权益提供方信息");
                    excelDomain.setSuccess("FALSE");
                    return excelDomain;
                }
                serviceDef.setServiceID(Util.getUUID().trim());
                serviceDef.setSupplierID(supplierID.trim());
                serviceDef.setServiceName(map.get("serviceName").toString().trim());
                serviceDef.setSupplierName(map.get("supplierName").toString().trim());
                serviceDef.setServiceProcess(map.get("serviceProcess").toString().trim());
                serviceDef.setServiceIntr(map.get("serviceIntr").toString().trim());
                serviceDef.setServiceChannel(map.get("serviceChannel").toString().trim());
                serviceDef.setTermOfValidity(termOfValidity.trim());
                serviceDef.setCreateTime(Util.getNowDate().trim());
                serviceDefs.add(serviceDef);
            }
        } catch (NumberFormatException numberFormatException) {
            excelDomain.setSuccess("FALSE");
            excelDomain.setMessage("导入失败,请检查日期格式" + numberFormatException.getMessage());
            return excelDomain;
        } catch (DataFormatException dataFormatException) {
            excelDomain.setSuccess("FALSE");
            excelDomain.setMessage("导入失败,请检查日期格式" + dataFormatException.getMessage());
            return excelDomain;
        } catch (Exception e) {
            excelDomain.setSuccess("FALSE");
            excelDomain.setMessage("导入失败,请检查EXCEL文件。" + e.getMessage());
            return excelDomain;
        }
        excelDomain.setSuccess("SUCCESS");
        excelDomain.setMessage("导入成功");
        excelDomain.setServiceDefList(serviceDefs);
        return excelDomain;
    }

    /**
     * 客户导出
     * 余照洋  任务
     */
    @GetMapping(value = "/downloadCustomer")
    @CrossOrigin
    public ResponseEntity<byte[]> downloadCustomer(CustomerModel customerModel) throws UnsupportedEncodingException {

//        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
//        Long deptID = loginUser.getUser().getDeptId();
        Long deptID = customerModel.getDeptID();

        String keys[] = {"customerID", "custName", "gender", "certID", "phoneNumber", "custStatus", "remnPoint", "usedPoint", "firstEffTime", "lastUseTime"};//列名

        String columnNames[] = {"客户号", "客户名称", "性别", "证件号", "手机号", "客户状态", "可用积分", "已用积分", "首单生效时间", "最近使用时间"};//列名

        PageInfo pi = customerService.getCustomerDomain(customerModel, String.valueOf(deptID), false, 1, 9999999);
        List<CustomerDomain> dataList = pi.getList();
        File excelFile = null;
        try {
            excelFile = ExcelHelper.writeXlsx(keys, columnNames, dataList, customerModel.getHidePrivate());
        } catch (Exception e) {
            e.printStackTrace();
        }
        byte[] ret = getFileByte(excelFile);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", new String("客户列表.xlsx".getBytes("GBK"), "ISO-8859-1"));
        return new ResponseEntity<byte[]>(ret, headers, HttpStatus.OK);

    }



    /**
     * 供应商客户导出
     * 余照洋  任务
     */
    @GetMapping(value = "/downloadSupplierCust")
    public ResponseEntity<byte[]> downloadSupplierCust(CustomerServiceConsumeQuery query) throws UnsupportedEncodingException {
        String keys[] = {"chanel", "customerID", "customerName", "gender", "identity", "phoneNumber", "policyNumber", "serviceName", "custStatus", "usedCount", "lastUseDate", "dueTime",};//列名
        String columnNames[] = {"渠道", "客户号", "客户名称", "性别", "证件号", "手机号", "保单号", "服务名称", "用户状态", "使用次数", "使用日期", "生效时间"};//列名
        PageRequest pr = PageRequest.of(0, 9999999);
        Page<SupplierCustomerDTO> page = customerServiceConsumeService.queryList(query, pr);
        List<SupplierCustomerDTO> dataList = page.getContent();
        File excelFile = null;
        try {
            excelFile = ExcelHelper.writeXlsx(keys, columnNames, dataList, query.getHidePrivate());
        } catch (Exception e) {
            e.printStackTrace();
        }
        byte[] ret = getFileByte(excelFile);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", new String("供应商客户列表.xlsx".getBytes("GBK"), "ISO-8859-1"));
        return new ResponseEntity<byte[]>(ret, headers, HttpStatus.OK);


//        //待下载文件名
//        //设置为png格式的文件
//        response.setHeader("content-type", "excel/xlsx");
//        response.setContentType("application/octet-stream");
//        response.setHeader("Content-Disposition", "attachment; filename=客户列表.xlsx");
//        byte[] buff = new byte[1024];
//        //创建缓冲输入流
//        BufferedInputStream bis = null;
//        OutputStream outputStream = null;
//
//        try {
//            outputStream = response.getOutputStream();
//
//            //这个路径为待下载文件的路径
//            bis = new BufferedInputStream(new FileInputStream(excelFile));
//            int read = bis.read(buff);
//
//            //通过while循环写入到指定了的文件夹中
//            while (read != -1) {
//                outputStream.write(buff, 0, buff.length);
//                outputStream.flush();
//                read = bis.read(buff);
//            }
//        } catch ( IOException e ) {
//            e.printStackTrace();
//            //出现异常返回给页面失败的信息
////            model.addAttribute("result","下载失败");
//        } finally {
//            if (bis != null) {
//                try {
//                    bis.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//            if (outputStream != null) {
//                try {
//                    outputStream.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }


        //成功后返回成功信息
//        model.addAttribute("result","下载成功");
//        return "employee/EmployeeDownloadFile";
    }

    private byte[] getFileByte(File file) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
        BufferedInputStream in = null;
        byte[] ret = null;
        try {
            in = new BufferedInputStream(new FileInputStream(file));
            int buf_size = 1024;
            byte[] buffer = new byte[buf_size];
            int len = 0;
            while (-1 != (len = in.read(buffer, 0, buf_size))) {
                bos.write(buffer, 0, len);
            }
            return bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
